<template>
  <el-form 
    ref="formRef" 
    :model="formData" 
    :rules="rules" 
    label-position="top" 
    class="courier-form"
  >
    <div class="form-header">
      <h3>{{ isEdit ? '编辑配送员' : '新增配送员' }}</h3>
    </div>
    
    <div class="form-body">
      <div class="basic-info">
        <h4>基本信息</h4>
        
        <div class="avatar-upload">
          <el-avatar :size="80" :src="formData.avatar">
            {{ formData.name ? formData.name.substring(0, 1) : '头' }}
          </el-avatar>
          <el-button size="small" @click="handleAvatarUpload">
            上传头像
          </el-button>
          <input 
            type="file" 
            ref="avatarInput" 
            style="display: none" 
            accept="image/*"
            @change="onAvatarSelected" 
          />
        </div>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="formData.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="工号" prop="id">
              <el-input 
                v-model="formData.id" 
                placeholder="请输入工号" 
                :disabled="isEdit" 
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="formData.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="工作状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择工作状态" style="width: 100%">
                <el-option label="在职" value="active" />
                <el-option label="休假" value="onLeave" />
                <el-option label="离职" value="inactive" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属区域" prop="area">
              <el-select v-model="formData.area" placeholder="请选择所属区域" style="width: 100%">
                <el-option v-for="area in areaOptions" :key="area.value" :label="area.label" :value="area.value" />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="入职日期" prop="joinDate">
              <el-date-picker 
                v-model="formData.joinDate"
                type="date"
                placeholder="选择入职日期"
                style="width: 100%"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      
      <el-divider />
      
      <!-- 扩展信息 -->
      <div class="extended-info">
        <h4>扩展信息</h4>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model="formData.idCard" placeholder="请输入身份证号" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="紧急联系人" prop="emergencyContact">
              <el-input v-model="formData.emergencyContact" placeholder="请输入紧急联系人" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="紧急联系人电话" prop="emergencyPhone">
              <el-input v-model="formData.emergencyPhone" placeholder="请输入紧急联系人电话" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="住址" prop="address">
              <el-input v-model="formData.address" placeholder="请输入住址" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="备注" prop="remarks">
          <el-input 
            v-model="formData.remarks" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入备注信息" 
          />
        </el-form-item>
      </div>
      
      <el-divider />
      
      <!-- 配送能力设置 -->
      <div class="delivery-settings">
        <h4>配送能力设置</h4>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="配送区域" prop="deliveryAreas">
              <el-select 
                v-model="formData.deliveryAreas" 
                multiple 
                placeholder="请选择配送区域" 
                style="width: 100%"
              >
                <el-option 
                  v-for="area in deliveryAreaOptions" 
                  :key="area.value" 
                  :label="area.label" 
                  :value="area.value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="配送能力 (单/天)" prop="deliveryCapacity">
              <el-input-number 
                v-model="formData.deliveryCapacity" 
                :min="1" 
                :max="100" 
                style="width: 100%" 
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否可配送特殊物品" prop="canDeliverSpecial">
              <el-switch v-model="formData.canDeliverSpecial" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="是否可配送大件物品" prop="canDeliverLarge">
              <el-switch v-model="formData.canDeliverLarge" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </div>
    
    <div class="form-footer">
      <el-button @click="emit('cancel')">取消</el-button>
      <el-button type="primary" @click="submitForm">保存</el-button>
    </div>
  </el-form>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

const props = defineProps({
  courierData: {
    type: Object,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})

// 区域选项
const areaOptions = [
  { value: '华东区', label: '华东区' },
  { value: '华南区', label: '华南区' },
  { value: '华北区', label: '华北区' },
  { value: '西南区', label: '西南区' },
  { value: '西北区', label: '西北区' },
  { value: '东北区', label: '东北区' }
]

// 配送区域选项
const deliveryAreaOptions = [
  { value: '上海市', label: '上海市' },
  { value: '北京市', label: '北京市' },
  { value: '广州市', label: '广州市' },
  { value: '深圳市', label: '深圳市' },
  { value: '成都市', label: '成都市' },
  { value: '杭州市', label: '杭州市' },
  { value: '武汉市', label: '武汉市' },
  { value: '西安市', label: '西安市' },
  { value: '南京市', label: '南京市' },
  { value: '重庆市', label: '重庆市' }
]

// 表单数据
const formData = reactive({
  id: '',
  name: '',
  phone: '',
  area: '',
  status: 'active',
  joinDate: '',
  avatar: '',
  idCard: '',
  emergencyContact: '',
  emergencyPhone: '',
  address: '',
  remarks: '',
  deliveryAreas: [],
  deliveryCapacity: 20,
  canDeliverSpecial: false,
  canDeliverLarge: false
})

// 表单验证规则
const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  id: [
    { required: true, message: '请输入工号', trigger: 'blur' },
    { pattern: /^PS\d{5}$/, message: '工号格式为PS开头加5位数字', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择工作状态', trigger: 'change' }
  ],
  area: [
    { required: true, message: '请选择所属区域', trigger: 'change' }
  ],
  joinDate: [
    { required: true, message: '请选择入职日期', trigger: 'change' }
  ],
  idCard: [
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],
  emergencyPhone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  deliveryCapacity: [
    { required: true, message: '请输入配送能力', trigger: 'blur' }
  ]
})

// 表单引用
const formRef = ref<FormInstance>()
const avatarInput = ref<HTMLInputElement>()

// 监听props变化，更新表单数据
watch(() => props.courierData, (newValue) => {
  if (newValue && Object.keys(newValue).length > 0) {
    // 复制数据到表单
    Object.assign(formData, newValue)
  }
}, { immediate: true, deep: true })

// 点击上传头像
const handleAvatarUpload = () => {
  avatarInput.value?.click()
}

// 头像选择后的处理
const onAvatarSelected = (event: Event) => {
  const input = event.target as HTMLInputElement
  if (input.files && input.files[0]) {
    const file = input.files[0]
    // 在实际应用中，这里应该上传文件到服务器，获取URL
    // 这里简单模拟一下，使用本地URL
    const reader = new FileReader()
    reader.onload = (e) => {
      formData.avatar = e.target?.result as string
    }
    reader.readAsDataURL(file)
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate((valid, fields) => {
    if (valid) {
      // 实际应用中，这里应该调用API保存数据
      ElMessage.success(`${props.isEdit ? '更新' : '创建'}配送员成功`)
      emit('save', { ...formData })
    } else {
      console.log('表单验证失败:', fields)
      ElMessage.error('请完善表单信息')
    }
  })
}

// 定义组件事件
const emit = defineEmits(['save', 'cancel'])

// 组件挂载时初始化
onMounted(() => {
  // 如果是新增且没有ID，自动生成一个
  if (!props.isEdit && !formData.id) {
    // 实际应用中，这里应该由后端生成ID
    const randomNum = Math.floor(10000 + Math.random() * 90000)
    formData.id = `PS${randomNum}`
  }
})
</script>

<style scoped>
.courier-form {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
}

.form-header {
  margin-bottom: 24px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 16px;
}

.form-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.form-body {
  margin-bottom: 24px;
}

.form-body h4 {
  font-size: 16px;
  font-weight: 600;
  color: #409EFF;
  margin: 0 0 16px 0;
}

.avatar-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  margin-bottom: 20px;
}

.form-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style> 